package com.acme.bankapp.client;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class BankClientGUI extends JFrame {

	JPanel formPanel;

	JTextField clientName;
	JComboBox<String> clientGender;
	JComboBox<String> accountType;
	JTextField accountBalance;
	JTextField accountOverdraft;

	JButton sendButton;

	BankClient client;

	public BankClientGUI() {
		
		try {
			client = new BankClient("localhost", 2013);
		} catch (IOException e) {
			showError("Unable to connect to server.\nApplication will be closed.\n");
			System.exit(0);
		}
		
		initUI();

		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				try {
					client.send("exit");
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void showMessage(String msg) {
		JOptionPane.showMessageDialog(this, msg, "Result", JOptionPane.INFORMATION_MESSAGE);
	}
	
	private void showError(String msg) {
		JOptionPane.showMessageDialog(this, msg, "Error", JOptionPane.ERROR_MESSAGE);
	}
	
	private void initUI() {
		formPanel = new JPanel();

		clientName = new JTextField();
		clientGender = new JComboBox<>(new String[] { "Male", "Female" });
		accountType = new JComboBox<>(new String[] { "Saving", "Checking" });
		accountBalance = new JTextField();
		accountOverdraft = new JTextField();
		accountOverdraft.setEditable(false);
		sendButton = new JButton("Send");

		formPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		formPanel.setLayout(new GridLayout(6, 2, 5, 5));

		formPanel.add(new JLabel("Name:"));
		formPanel.add(clientName);

		formPanel.add(new JLabel("Gender:"));
		formPanel.add(clientGender);

		formPanel.add(new JLabel("Account type:"));
		formPanel.add(accountType);

		formPanel.add(new JLabel("Balance:"));
		formPanel.add(accountBalance);

		formPanel.add(new JLabel("Overdraft:"));
		formPanel.add(accountOverdraft);

		formPanel.add(new JLabel(""));
		formPanel.add(sendButton);

		accountType.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String strAccountType = accountType.getItemAt(accountType.getSelectedIndex());
				boolean enableOverdraftField = true;
				if ("Saving".equalsIgnoreCase(strAccountType)) {
					enableOverdraftField = false;
				}
				accountOverdraft.setEditable(enableOverdraftField);
			}
		});

		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				send();
			}
		});

		this.add(formPanel);

		setTitle("New client");
		setSize(300, 200);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	private void send() {
		String feedStr = createFeedStringFromFields();
		String cmd = String.format("add %s", feedStr);

		String response;

		try {
			response = client.send(cmd);
			showMessage(response);
		} catch (IOException e) {
			response = String.format("%s%n%s%n",
					e.getMessage(),
					e.getStackTrace());
			showError(response);
		}

	}

	private String createFeedStringFromFields() {

		String strClientName = clientName.getText();

		String strClientGender = clientGender.getItemAt(clientGender
				.getSelectedIndex());
		char cClientGender = strClientGender.toLowerCase().charAt(0);

		String strAccountType = accountType.getItemAt(accountType
				.getSelectedIndex());
		char cAccountType = strAccountType.toLowerCase().charAt(0);

		String strBalance = accountBalance.getText();
		String strOverdraft = accountOverdraft.getText();

		StringBuilder sb = new StringBuilder();
		sb.append("accounttype=").append(cAccountType).append(";");
		sb.append("balance=").append(strBalance).append(";");
		if (cAccountType == 'c')
			sb.append("overdraft=").append(strOverdraft).append(";");
		sb.append("name=").append(strClientName).append(";");
		sb.append("gender=").append(cClientGender).append(";");

		return sb.toString();
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				(new BankClientGUI()).setVisible(true);
			}
		});
	}

}
